<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select filterable @change="queryList()" v-model="queryParams.brandId" class="zs-select-md zs-space-right-sm"
          placeholder="品牌" clearable remote remote-show-suffix :remote-method="(name) => name && getBrandDownList(name)">
          <el-option v-for="item in brandDownList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-select @change="queryList()" v-model="queryParams.firstFormat" class="zs-select-md zs-space-right-sm"
          placeholder="业态" clearable>
          <el-option v-for="item in brandFirstBizTypes" :key="item.id" :label="item.dicName" :value="item.id" />
        </el-select>
        <el-button @click="queryList()" class="zs-btn-plain">查询</el-button>
      </span>
      <span>
        <el-button class="zs-btn-plain" @click="handleDownload">
          <el-icon class="el-icon--left">
            <Upload />
          </el-icon>导出
        </el-button>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <hsPageTable :loading="tableData.loading" :total="tableData.total" :tableData="tableData.data"
        :cloumns="tableData.cloumns" @pageChange="pageChange" @onSortChange="tableSortChange">
        <template #bottomTip>
          <div class="zs-text-gray-dark zs-text-sm zs-space-top">*数据区间：{{ curDate }}；销售额：万元；月均坪效：元/平米/月</div>
        </template>
      </hsPageTable>
    </div>
  </div>
</template>

<script setup lang="jsx">
// import PageTable from "@/components/page-table.vue"
import dbPublicApi from '@/api/dbPublic'
import { toThousands } from '@/utils/number-util'
import { downloadNewFile } from '@/utils/publicUtils';
import { brandAnalysisApi } from '@/api/SpecialReport/index'
import { reactive, ref } from "vue"
import { useRouter } from 'vue-router'
import { useStore } from "vuex";
let store = useStore();
let router = useRouter();
const curPageSize = ref(store.state.uiPageSizeDefault);

let curDate = ref('')
const queryDataUpdateTime = async () => {
  await dbPublicApi.queryMonthsTimeApi().then(res => {
    if (res.data.code == 200) {
      queryParams.endYear = res.data.data.split('-')[0]
      curDate.value = `${Number(queryParams.endYear) - 2}年-${queryParams.endYear}年`
    }
  })
}

// 查询条件
let queryParams = reactive({
  brandId: '',
  firstFormat: '',
  orderBy: [],
  endYear: '',
  pageNo: 1,
  pageSize: curPageSize
})
// 表格数据
let tableData = reactive({
  loading: false,
  data: [],
  total: 0,
  cloumns: [
    {
      prop: 'wtBrandname', label: '品牌', align: 'left', type: 'html',
      render: ({ row }) => {
        return <span class="zs-link" onClick={() => jumpDetailPage(row)}>{row.wtBrandname}</span>
      }
    },
    { prop: 'firstFormatName', label: '业态', align: 'center', width: '100' },
    { prop: 'cnProject', label: '合作项目', align: 'center', width: '100' },
    { prop: 'cnContracts', label: '租赁合同', align: 'center', width: '100' },
    {
      prop: 'smSales', label: '销售额', align: 'right', sort: true,
      type: 'customMethods', methods: (row, empty) => row.smSales ? toThousands(row.smSales) : empty
    },
    {
      prop: 'avMonthSales', label: '月均销售额', align: 'right', sort: true,
      type: 'customMethods', methods: (row, empty) => row.avMonthSales ? toThousands(row.avMonthSales) : empty
    },
    {
      prop: 'monAvPlEff', label: '月均坪效', align: 'right', sort: true,
      type: 'customMethods', methods: (row, empty) => row.monAvPlEff ? toThousands(row.monAvPlEff) : empty
    },
    {
      prop: 'smInvrecamtl', label: '租费', align: 'right', sort: true,
      type: 'customMethods', methods: (row, empty) => row.smInvrecamtl ? toThousands(row.smInvrecamtl) : empty
    },
    {
      prop: 'rentSaleRPx', label: '租售比', align: 'right', sort: true,
      type: 'customMethods', methods: (row, empty) => row.rentSaleRPx ? (row.rentSaleRPx * 100).toFixed(2) + '%' : empty,
    },
  ]
})

function tableSortChange(val) {
  let curSortColumn = []
  val.forEach(el => {
    let curKey = el.prop.replace(/[A-Z]/g, '_$&').toLowerCase()
    let curType = curKey + ',' + el.type
    curSortColumn.push(curType)
  })
  queryParams.orderBy = curSortColumn
  queryList()
}

// function jumpDetailPage(row) {
//   let query = {
//     rid: 'SpecialReport_BrandAnalysis_DetailList_page',
//     rTitle: '品牌分析明细',
//     brandId: row.wtBrandId,
//     brandName: row.wtBrandname,
//   }
//   if (process.env.NODE_ENV == 'development') {
//     router.push({
//       path: '/SpecialReport/brandAnalysis/detailList',
//       query,
//     })
//   } else {
//     router.push({
//       path: '/page/routeController/index',
//       query,
//     })
//   }
// }

function jumpDetailPage(row) {
  let query = {
    rid: 'SpecialReport_BrandAnalysis_PerformanceList_page',
    rTitle: '品牌业绩页',
    brandId: row.wtBrandId,
    brandName: row.wtBrandname,
  }
  if (process.env.NODE_ENV == 'development') {
    router.push({
      path: '/SpecialReport/brandAnalysis/performanceList',
      query,
    })
  } else {
    router.push({
      path: '/page/routeController/index',
      query,
    })
  }
}

// 分页变化
function pageChange(page) {
  queryParams.pageNo = page.current
  queryParams.pageSize = page.pageSize
  queryList()
}
function queryList() {
  tableData.loading = true
  let params = Object.assign({}, queryParams)
  params.brandId = params.brandId || 'all'
  params.firstFormat = params.firstFormat || 'all'
  brandAnalysisApi.queryBrandAnalysisListApi(params).then(res => {
    let resData = res.data
    if (resData.errorCode == 200) {
      tableData.data = resData.data
      tableData.total = resData.totalCount
    }
    tableData.loading = false
  })
}


let brandDownList = ref([])
function getBrandDownList(name) {
  let curParams = name ? { name, typeCode: 'pp' } : { typeCode: 'pp', pageNo: 1, pageSize: 10 }
  brandAnalysisApi.queryBrandDownListApi(curParams).then(res => {
    let resData = res.data
    if (resData.errorCode == 200) {
      brandDownList.value = resData.data;
    }
  })
}


let brandFirstBizTypes = ref([])
function getBrandfirstBizType() {
  dbPublicApi.queryDict({ dicTypes: ["WIN_BIZ_TYPE_LEVEL_1"] }).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      brandFirstBizTypes.value = resData.data.WIN_BIZ_TYPE_LEVEL_1;
    }
  })
}

//导出
const handleDownload = async () => {
  let params = Object.assign({}, queryParams)
  params.brandId = params.brandId || 'all'
  params.firstFormat = params.firstFormat || 'all'
  const fileName = `品牌分析.xls`;
  let fileData = await brandAnalysisApi.brandExportApi(params);
  downloadNewFile(fileData.data, fileName);
};

const init = async () => {
  getBrandDownList()
  getBrandfirstBizType()
  await queryDataUpdateTime()
  queryList()
}
init()
</script>

<style lang="scss" scoped>
:deep(.el-table__row .zs-link) {
  cursor: pointer !important;
}
</style>
